<?php

namespace app\home\controller;

use think\captcha\Captcha;
// use think\captcha\Captcha;

use think\Controller;
use think\Db;
use think\Request;

class Index extends Controller
{
    public function __construct()
    {
        //手动继承父级
        parent::__construct();
        $this->UserModel = model('User.user');
        $this->RecordModel = model('Record');
        $this->PostModel = model('Post.Post');

        // 获取用户表所有数据
        $UserList = model('User.User')->column('id,salt');

        // 获取cookie的数据
        $LoginUser = cookie('LoginUser') ? cookie('LoginUser') : '';

        // 存放id的字符串
        $userid = 0;

        foreach ($UserList as $key => $value) {
            $UserSalt = md5($key . $value);

            if ($LoginUser == $UserSalt) {
                $userid = $key;
                break;
            }
        }

        // 根据id去查询用户表 对象 => 数组 > toArray()
        $User = model('User.User')->find($userid);
        // $User = Db::table('pre_user')->find($userid);

        $userid = isset($User['id']) ? $User['id'] : 0;

        $User = $User ? $User : [];

        // 把用户数据给继承home公共控制器的子控制器
        $this->LoginUser = $User;


        //  $regionList = model('Region')->where(['province' => $this->LoginUser['province']])->find(); 
        // 赋值视图
        $this->assign([
            'LoginUser' => $User,
        ]);
    }

    public function index()
    {

        // return view();
        //接收分类id -> 帖子 -> 根据分类id去查询相对应的帖子
        $cateid = $this->request->param('cateid', '');

        //帖子状态
        $state = $this->request->param('state', '');

        //采纳
        $accept = $this->request->param('accept', 0);

        //关键字
        $keyword = $this->request->param('keyword', '');

        //条件数组
        $where = [];
        if (!empty($cateid)) {
            $where["cateid"] = $cateid;
        }
        if (!empty($state)) {
            $where["state"] = $state;
        }
        if ($accept == 0) {
            // where `accept` is null
            $where['accept'] = ['exp', Db::raw('is null')];
        } elseif ($accept == 1) {
            $where['accept'] = ['exp', Db::raw('is not null')];
        }
        if (!empty($keyword)) {
            $where['title'] = ['like', "%$keyword%"];
        }

        // 查询签到积分
        $SignPoint = model('config')->where('key', 'SignPoint')->value('value');

        $CateList = model('Post.Cate')->order('weigh', 'desc')->limit(7)->select();

        //查询本周热议
        $HotPostList = model('Post.Comment')
            ->with(['post'])
            ->field('COUNT(*) as num, comment.postid')
            ->group('comment.postid')
            ->where('post.deletetime', null)
            ->whereTime('comment.createtime', 'week')
            ->order('num desc')
            ->limit(5)
            ->select();
        // halt($HotTopicList);

        //本周回贴
        $HotUserList = model('Post.Comment')
            ->with(['user'])
            ->field('COUNT(*) as num, comment.userid')
            ->group('comment.userid')
            ->where('user.deletetime', null)
            ->whereTime('comment.createtime', 'week')
            ->order('num desc')
            ->limit(5)
            ->select();

        $PostList = model('Post.Post')->with(['user', 'cate'])->where($where)->order('post.createtime', 'desc')->paginate(6, false, ['query' => Request::instance()->param()]);
        // halt($PostList[0]);
        return $this->fetch('', [
            'CateList' => $CateList,
            'cateid' => $cateid,
            'PostList' => $PostList,
            'HotPostList' => $HotPostList,
            'HotUserList' => $HotUserList,
            'SignPoint' => $SignPoint,
            'state' => $state,
            'accept' => $accept
        ]);
    }

    //帖子详情
    public function info()
    {
        $postid = $this->request->param('postid', 0);
        $userid = !empty($this->LoginUser['id']) ? $this->LoginUser['id'] : 0;

        //收藏逻辑（查询该贴子是否）
        $CollectId = model('Collect')->where(['postid' => $postid, 'userid' => $userid])->value('id');
        // halt($CollectId);

        $post = $this->PostModel->with(['user', 'cate'])->where('post.id', $postid)->find();

        if (!$post) {
            $this->error('帖子不存在，请重新选择。');
        }

        //按浏览量id进行更新

        $User = $this->UserModel->find($userid);
        //字符串转数组
        $VisitArr = explode(',', $post['visit']);

        if ($User) {

            if (!in_array($User['id'], $VisitArr)) {
                $VisitArr[] = $User['id'];

                $VisitArr = implode(',', $VisitArr);

                //把字符串的左边逗号去掉
                $VisitArr = ltrim($VisitArr, ',');

                $this->PostModel->where('id', $postid)->update(['visit' => $VisitArr]);
            }
        }

        //刷新浏览量的另一个方法
        $VisitCount = is_array($VisitArr) ? count($VisitArr) : 1;

        //刷新浏览量的另一个方法
        // $post = $this->PostModel->with(['user','cate'])->where('post.id',$postid)->find();

        $cateid = $this->request->param('cateid', '');
        //帖子状态
        $state = $this->request->param('state', '');
        //采纳
        $accept = $this->request->param('accept', 0);
        $where = [];
        if (!empty($cateid)) {
            $where["cateid"] = $cateid;
        }
        if (!empty($state)) {
            $where["state"] = $cateid;
        }
        if ($accept == 0) {
            // where `accept` is null
            $where['accept'] = ['exp', Db::raw('is null')];
        } elseif ($accept == 1) {
            $where['accept'] = ['exp', Db::raw('is not null')];
        }

        //查询本周热议
        $HotPostList = model('Post.Comment')
            ->with(['post'])
            ->field('COUNT(*) as num, comment.postid')
            ->group('comment.postid')
            ->where('post.deletetime', null)
            ->whereTime('comment.createtime', 'week')
            ->order('num desc')
            ->limit(5)
            ->select();

        $CateList = model('Post.Cate')->order('weigh', 'desc')->limit(7)->select();

        //查询评论数据
        $CommentList = model('Post.Comment')->with('user')->where("postid", $postid)->order("comment.createtime")->select();
        $CommentList = CommentTree($CommentList, 0, $User);
        return $this->fetch('', [
            'CateList' => $CateList,
            'cateid' => $cateid,
            'state' => $state,
            'accept' => $accept,
            'post' => $post,
            'HotPostList' => $HotPostList,
            'CollectId' => $CollectId,
            'VisitCount' => $VisitCount,
            'CommentList' => $CommentList
        ]);
    }

    //登录
    public function login()
    {
        // if(cookie('LoginUser'))$this->success('您已经成功登录',url('home/index/index'),'',3);
        $LoginUser = cookie('LoginUser') ? cookie('LoginUser') : '';
        if ($LoginUser) {
            $this->success('您已经成功登录', url('home/index/index'));
        }
        //判断是否是post请求
        if ($this->request->isPost()) {
            $params = $this->request->param();

            if (!captcha_check($params['vercode'])) {
                $this->error('验证码错误');
            }
            //通过用户名去查询数据库是否存在该用户
            $User = $this->UserModel->where(['email' => $params['email']])->find();

            //查询出来的结果为空， 说明该用户不存在
            if (!$User) {
                $this->error('该用户不存在');
            }
            $password = md5($params['pass'] . $User['salt']);

            if ($password != $User['password']) {
                $this->error('密码错误');
            }

            //设置cookie
            $data = md5($User['id'] . $User['salt']);
            cookie('LoginUser', $data);
            $this->success('登录成功', url('home/user/index'));
        }
        //输出视图
        return $this->fetch();
    }

    //注册
    public function register()
    {
        $LoginUser = cookie('LoginUser') ? cookie('LoginUser') : '';
        if ($LoginUser) {
            $this->success('您已经成功登录', url('home/index/index'));
        }
        //get post 
        if ($this->request->isPost()) {
            $params = $this->request->param();
            //自带中断
            // // halt($params);
            // if(Captcha_check)
            if (!captcha_check($params['vercode'])) {
                $this->error('验证码错误');
            }
            //判断密码和确认密码是否一致
            if ($params['pass'] != $params['repass']) {
                $this->error('密码与确认密码不一致');
            }
            // 生成密码盐
            $salt = build_ranstr();

            // 进行加密
            $password = md5($params['pass'] . $salt);

            // Db类或者模型增删改查 用Db类查询注册的赠送积分
            $point = model('Config')->where('key', 'RegisterPoint')->value('value');
            // halt($point);

            // 封装插入数据库的数组
            $data = [
                'email' => $params['email'],
                'nickname' => $params['nickname'],
                'password' => $password,
                // 'createtime' => $params['createtime'],
                'salt' => $salt,
                'sex' => 0,
                'auth' => 0,
                'vip' => 1,
                'point' => $point
            ];
            // halt($data);

            $result = $this->UserModel->validate('common/User/User')->save($data);
            $userId = $this->UserModel->getLastInsID();
            $sign_data = [
                'userId' => $userId,
                'num' => 0,
                'signTime' => null,
                'addTime' => null,
            ];
            // halt($sign_data);
            $resultSign = model('SignIn')->insert($sign_data);
            if ($result === FALSE || $resultSign === FALSE) {
                $this->error($this->UserModel->getError());
            } else {
                $this->success('注册成功', url('home/index/login'));
            }
        }


        return $this->fetch();
    }

    /**
     * 验证邮箱
     *
     * @return \think\Response
     */
    public function auth()
    {
        $email = $this->request->param('email');

        $UserList = $this->UserModel->column('email,salt');

        //定义字符串
        $UserEmail = '';

        foreach ($UserList as $key => $value) {
            $userSalt = md5($key . $value);
            if ($email == $userSalt) {
                $UserEmail = $key;
                break;
            }
        }

        // $User = $this->UserModel->where('email',$UserEmail)->find();
        $User = $this->UserModel->where('email', $UserEmail)->find();

        if (!$User) {
            $this->error('无效邮箱');
        }

        $data = [
            'id' => $User['id'],
            'auth' => 1
        ];

        // isUpdate(true) => 更新操作
        $result = $this->UserModel->isUpdate(true)->save($data);

        if ($result == FALSE) {
            $this->error('认证失败');
        } else {
            cookie('LoginUser', md5($User['id'] . $User['salt']));
            $this->success('认证成功', url('home/user/index'));
        }

        // return $this->fetch('', [
        //     'navTitle' => 
        // ]);
    }

    //验证码
    public function vercode()
    {
        $config = [
            'fontSize' => 20,
            'imageW' => 150,
            'imageH' => 40,
            'length' => 4,
            // 关闭验证码杂点
            'useNoise' => false,
        ];
        $captcha = new Captcha($config);
        $captcha->useImgBg = true;
        $captcha->fontttf = '4.ttf';
        return $captcha->entry();
    }
}
